<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>产品管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- 搜索用户框 -->
                <el-input v-model="query.param.title" placeholder="套餐名称" class="handle-input mr10"></el-input>
                <!-- 搜索按钮 -->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <!-- 添加产品 -->
                <el-button type="primary" icon="el-icon-search" @click="addProduct">添加旅游项目</el-button>
            </div>
            <!-- 产品列表 -->
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <!-- <el-table-column type="selection" width="60" align="center" prop="id"></el-table-column> -->
                <!-- 产品名称 -->
                <el-table-column prop="title" label="名称" align="center" :show-overflow-tooltip="true"></el-table-column>

                <!-- 副标题 -->
                <el-table-column prop="subTitle" label="详细" align="center"
                                 :show-overflow-tooltip="true"></el-table-column>

                <el-table-column prop="lable" label="目的地" align="center"
                                 :show-overflow-tooltip="true"></el-table-column>

                <el-table-column prop="ageLimit" label="年龄限制" align="center"
                                 :show-overflow-tooltip="true"></el-table-column>

                <!-- 操作 -->
                <el-table-column label="操作" align="center" width="245">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >产品更改
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="priceList(scope.$index, scope.row)"
                        >价格列表
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="priceAdd(scope.$index, scope.row)"
                        >添加价格
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 页码功能 -->
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageNum"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <el-dialog :title="title" :visible.sync="listPrices" width="85%">
            <el-table
                    :data="priceLists"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <!-- <el-table-column prop="id" label="主键id" align="center"></el-table-column> -->
                <el-table-column prop="specifications" label="规格比如6天五晚" align="center"></el-table-column>
                <el-table-column prop="price" label="商品价格" align="center"></el-table-column>
                <el-table-column prop="voucherPrice" label="优惠价格" align="center"></el-table-column>
                <el-table-column prop="logisticsPrice" label="快递费用" align="center"></el-table-column>
                <el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" @click="stateClick(scope.row)"
                                   :class="scope.row.status === 1 ? '' : 'gray'">{{scope.row.status === 1 ? '上架' :
                            '下架'}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="banlanceNumber" label="剩余数量" align="center"></el-table-column>
                <el-table-column prop="limitPerOrder" label="每单购买限制数量" align="center"></el-table-column>
                <el-table-column prop="startTime" label="开始售卖时间" align="center"></el-table-column>
                <el-table-column prop="endTime" label="结束售卖时间" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="245">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="priceDetails(scope.$index, scope.row)"
                        >详情
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="browser(scope.$index, scope.row)"
                        >浏览
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 新增编辑 -->
        <el-dialog :title="title" :visible.sync="addPrices" width="85%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="规格">
                    <el-input v-model="form.specifications" placeholder="规格 比如6天五晚"></el-input>
                </el-form-item>
                <el-form-item label="商品价格">
                    <el-input v-model="form.price" placeholder="商品价格"></el-input>
                </el-form-item>
                <el-form-item label="优惠价格">
                    <el-input v-model="form.voucherPrice" placeholder="优惠价格"></el-input>
                </el-form-item>
                <el-form-item label="快递费用">
                    <el-input v-model="form.logisticsPrice" placeholder="快递费用 0-包邮"></el-input>
                </el-form-item>
                <el-form-item label="商品状态">
                    <el-input v-model="form.status" placeholder="商品状态 0-下架 1-上架 2-删除"></el-input>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input v-model="form.banlanceNumber" placeholder="剩余数量"></el-input>
                </el-form-item>
                <el-form-item label="限制">
                    <el-input v-model="form.limitPerOrder" placeholder="每单购买限制数量0为不限制"></el-input>
                </el-form-item>
                <el-form-item label="开始售卖时间">
                    <el-col :span="11">
                        <el-date-picker
                                type="date"
                                placeholder="开始售卖时间"
                                v-model="form.startTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                style="width: 100%;"
                        ></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="结束售卖时间">
                    <el-col :span="11">
                        <el-date-picker
                                type="date"
                                placeholder="结束售卖时间"
                                v-model="form.endTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                style="width: 100%;"
                        ></el-date-picker>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addPrices = false">取 消</el-button>
                <el-button type="primary" @click="add(form)">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑（修改）的弹出框 -->
        <el-dialog :title="title" :visible.sync="editVisible" width="85%">
            <el-form ref="form" :model="form" label-width="70px">

                <el-form-item label="位置">
                    <el-select placeholder="请选择" v-model="form.view">
                        <el-option key="0" label="全部" value="0"></el-option>
                        <el-option key="1" label="推荐" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题">
                    <el-input v-model="form.title" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="副标题">
                    <el-input v-model="form.subTitle" placeholder="副标题"></el-input>
                </el-form-item>
                <el-form-item label="视频地址">
                    <el-input v-model="form.videoUrl" placeholder="请输入视频地址"></el-input>
                </el-form-item>
                <el-form-item label="目的地">
                    <el-input v-model="form.lable" placeholder="目的地"></el-input>
                </el-form-item>
                <!-- 年龄权限 -->
                <el-form-item label="年龄限制">
                    <el-input v-model="form.ageLimit" placeholder="年龄权限0-3岁、10-15岁等" type="number"></el-input>
                </el-form-item>
                <el-form-item label="展示图">
                    <el-upload
                            class="avatar-uploader"
                            :headers="myHeaders"
                            :action="uploadsrc"
                            accept="image/jpeg,image/gif,image/png"
                            list-type="picture-card"
                            :limit="1"
                            :before-upload="handleBeforeUpload"
                            :on-success="uploadLogoSuccess"
                            :on-error="uploadError"
                            :data="pdfData"
                            :file-list="logolist"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="form.listLogo">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="轮播图">
                    <el-upload
                            class="avatar-uploader"
                            :headers="myHeaders"
                            :action="uploadsrc"
                            accept="image/jpeg,image/gif,image/png"
                            list-type="picture-card"
                            :limit="6"
                            :before-upload="handleBeforeUpload"
                            :on-success="uploadSuccess"
                            :on-error="uploadError"
                            :on-remove="handleRemove"
                            :data="pdfData"
                            :file-list="imglist"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="form.detailBanner">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="保障说明">
                    <quill-editor ref="myTextEditor" v-model="form.securityStatement"
                                  @change="securityStatementHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="服务说明">
                    <quill-editor ref="myTextEditor" v-model="form.serviceDescription"
                                  @change="serviceDescriptionHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="行程说明">
                    <quill-editor ref="myTextEditor" v-model="form.itineraryDescription"
                                  @change="itineraryDescriptionHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="产品亮点">
                    <quill-editor ref="myTextEditor" v-model="form.productHighlights"
                                  @change="productHighlightsHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="费用说明">
                    <quill-editor ref="myTextEditor" v-model="form.costDescription"
                                  @change="costDescriptionHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="预定说明">
                    <quill-editor ref="myTextEditor" v-model="form.reserveDescription"
                                  @change="reserveDescriptionHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="商品详情">
                    <quill-editor ref="myTextEditor" v-model="form.introduce" @change="introduceHtml"></quill-editor>
                </el-form-item>
                <el-form-item label="目的地">
                    <el-input v-model="form.remark" placeholder="备注"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateClick(form)">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<!-- 功能实现 -->
<script>
    import md5 from 'js-md5';
    // 富文本
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import { quillEditor } from 'vue-quill-editor';
    import { uploadsrc } from '../../../utils/dcf2d0812e764796a97bb2e8c1725fab.js';
    import { dynamicHeader } from '../../../utils/dcf2d0812e764796a97bb2e8c1725fab.js';

    export default {
        name: 'basetable',
        data() {
            return {
                query: {
                    pageNum: 1,
                    pageSize: 10,
                    param: {
                        title: '',
                        distributorUserId: ''
                    }
                },
                uploadsrc: '',
                tableData: [],
                priceLists: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                updateVisible: false,
                listPrices: false,
                addPrices: false,
                pageTotal: 0,
                idx: -1,
                id: -1,
                dropDownData: [],
                categoryId: '',
                cate: [],
                form: {},
                submit: {
                    detailBanner: ''
                },
                categoty: [],
                status: 0,
                dialogImageUrl: '',
                imageUrl: '',
                dialogVisible: '',
                formLabelWidth: '80px',
                myHeaders: {},
                pdfData: {
                    type: 1,
                    path: 1
                },
                imglist: [],
                logolist: [],
                title: '编辑',
                distributorIds: [],
                parentids: [],
                categoryIds: [],
                level: 1,
                parentId: 0,
                parentid: 0,
                goodsId: '',
                ortool: false,
                viweList: {},
                view: [{
                    id: 0,
                    name: '全部'
                }, {
                    id: 1,
                    name: '推荐'
                }],

                goodsTypes: [{
                    type: 1,
                    name: '普通商品'
                }, {
                    type: 2,
                    name: '套餐商品'
                }]
            };
        },
        components: {
            quillEditor
        },
        created() {
            this.tablist();
            this.uploadsrc = uploadsrc;
        },
        methods: {
            getmyHeaders() {
                var dHeader = dynamicHeader();
                this.myHeaders.signature = dHeader.signature;
                this.myHeaders.nonce = dHeader.nonce;
                this.myHeaders.timestamp = dHeader.timestamp;
                this.myHeaders.appkey = dHeader.appkey;
                this.myHeaders.token = dHeader.token;
            },
            securityStatementHtml({ editor, html, text }) {
                this.form.securityStatement = html;
            },
            serviceDescriptionHtml({ editor, html, text }) {
                this.form.serviceDescription = html;
            },
            itineraryDescriptionHtml({ editor, html, text }) {
                this.form.itineraryDescription = html;
            },
            productHighlightsHtml({ editor, html, text }) {
                this.form.productHighlights = html;
            },
            costDescriptionHtml({ editor, html, text }) {
                this.form.costDescription = html;
            },
            reserveDescriptionHtml({ editor, html, text }) {
                this.form.reserveDescription = html;
            },
            introduceHtml({ editor, html, text }) {
                this.form.introduce = html;
            },
            handleBeforeUpload(file) {
                this.handleimgtype(file);
                if (this.form.distributorUserId == null) {
                    alert('请先选择分销商');
                } else {
                    this.pdfData.path = this.form.distributorUserId;
                    this.getmyHeaders();
                }
            },
            handleimgtype(file) {
                if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
                    this.$notify.warning({
                        title: '警告',
                        message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
                    });
                    return false;
                }
                let size = file.size / 1024 / 1024 / 2;
                if (size > 2) {
                    this.$notify.warning({
                        title: '警告',
                        message: '图片大小必须小于2M'
                    });
                    return false;
                }
            },
            uploadLogoSuccess(data) {
                if (data.returnCode == 200) {
                    this.form.listLogo = data.data;
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            // 文件超出个数限制时的钩子
            uploadSuccess(data) {
                if (data.returnCode == 200) {
                    if (this.form.detailBanner.length == 0) {
                        this.form.detailBanner = [];
                    }
                    this.form.detailBanner.push(data.data);
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            uploadError(data) {
                this.$message.success(`上传失败，请重新上传`);
            },
            // 首页菜单下拉
            dropdownViwe() {
                dropdownViwe().then(res => {
                    this.viweList = res.data;
                });
            },
            handleRemove(data) {
                var detailBanner = this.form.detailBanner;
                var index = detailBanner.indexOf(data.data);
                this.form.detailBanner.splice(index, 1);
            },
            //商品展示
            tablist() {
                goodsList(this.query).then(res => {
                    if (res.returnCode == 200) {
                        this.tableData = res.data.list;
                        this.pageTotal = res.data.total;
                    } else {
                        this.tableData = null;
                        this.pageTotal = 0;
                    }
                });
            },
            //下拉类型展示
            category() {
                listcategroys().then(res => {
                    this.dropDownData = res.data;
                });
            },
            //上架  下架功能
            stateClick(row) {
                //要传入要修改 主键id 和修改 状态的值
                updatePrice({
                    id: row.id,
                    status: row.status === 1 ? 0 : 1
                }).then(res => {
                    if (res.returnCode === 200) {
                        this.$message.success(row.status == 1 ? '下架成功' : '上架成功');
                        this.listprice(row.goodsId);
                    }
                }, err => {
                    console.log('err--', err);
                });
            },
            // 产品修改
            updateClick(row) {
                if (row.id) {
                    this.updategoods(row);
                } else {
                    this.addgoods(row);
                }
            },
            addgoods(row) {
                this.submit = row;
                var detailBanner = row.detailBanner.length > 1 ? row.detailBanner.join(',') : row.detailBanner[0];
                this.submit.detailBanner = detailBanner;
                addGoods(this.submit).then(res => {
                    if (res.returnCode === 200) this.tablist();
                    this.$message.success(`新增商品成功`);
                    this.editVisible = false;
                }, err => {
                    console.log('err--', err);
                });
            },
            updategoods(row) {
                this.submit = row;
                var detailBanner = row.detailBanner.length > 1 ? row.detailBanner.join(',') : row.detailBanner[0];
                this.submit.detailBanner = detailBanner;
                updateGoods(this.submit).then(res => {
                    if (res.returnCode === 200) this.tablist();
                    this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                    this.editVisible = false;
                }, err => {
                    console.log('err--', err);
                });
                this.$set(this.tableData, this.idx, this.form);
            },
            handleAvatarSuccess() {

            },
            beforeAvatarUpload() {

            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageNum', 1);
                this.tablist();
            },
            updateView() {
                this.title = '批量修改首页展示类型';
                this.updateVisible = true;

            },
            //点击商品添加
            addProduct() {
                this.title = '新增';
                this.form = {
                    detailBanner: [],
                    listLogo: ''
                };
                this.imglist = [];
                this.logolist = [];
                this.editVisible = true;
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                    })
                    .catch(() => {
                    });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                let str = '';
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error(`删除了${str}`);
                this.multipleSelection = [];
            },
            // 编辑操作
            handleEdit(index, row) {
                this.title = '编辑';
                this.idx = index;
                this.selectgoodsbyid(row.id);
            },
            //
            priceDetails(index, row) {
                this.title = '价格编辑';
                this.idx = index;
                this.detailsPrice(row.id);
            },

            detailsPrice(id) {
                detailsPrice(id).then(res => {
                    if (res.returnCode == 200) {
                        var row = res.data;
                        this.form = row;
                        this.addPrices = true;
                    }
                });
            },
            priceList(index, row) {
                this.title = '价格列表';
                this.idx = index;
                this.listprice(row.id);
            },
            listprice(id) {
                listPrice({
                    pageNum: 1,
                    pageSize: 10,
                    param: {
                        goodsId: id
                    }
                }).then(res => {
                    if (res.returnCode == 200) {
                        this.priceLists = res.data.list;
                        this.pageTotal = res.data.total;
                        this.listPrices = true;
                    } else {
                        this.$message.error('请添加价格');
                    }
                });
            },
            // 添加价格
            priceAdd(index, row) {
                this.title = '新增价格';
                this.idx = index;
                this.goodsId = row.id;
                this.form = {
                    goodsId: row.id
                };
                this.addPrices = true;
            },
            add(row) {
                if (row.id) {
                    this.updateprice(row);
                } else {
                    this.addPrice(row);
                }
            },
            updateprice(row) {
                updatePrice(row).then(res => {
                    if (res.returnCode == 200) {
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        this.listprice(row.goodsId);
                        this.addPrices = false;
                    }
                });
            },
            addPrice(row) {
                addPrice(row).then(res => {
                    if (res.returnCode == 200) {
                        this.$message.success(`新增价格成功!`);
                        this.addPrices = false;
                    }
                });
            },
            selectgoodsbyid(id) {
                detailsGoods(id).then(res => {
                    if (res.returnCode == 200) {
                        var row = res.data;
                        this.form = row;
                        this.imglist = [];
                        this.logolist = [];
                        this.parentid = row.parentId;
                        this.ortool = false;
                        if (row.detailBanner) {
                            var detailBanners = row.detailBanner.indexOf(',') > -1 ? row.detailBanner.split(',') : [row.detailBanner];
                            this.form.detailBanner = detailBanners;
                            for (var i = 0; i < detailBanners.length; i++) {
                                var detailBanner = {
                                    url: detailBanners[i]
                                };
                                this.imglist.push(detailBanner);
                            }
                        }
                        if (row.listLogo) {
                            this.logolist = [{
                                url: row.listLogo
                            }];
                        }
                        this.editVisible = true;
                    } else {

                    }
                });
            },
            // 保存编辑
            saveEdit() {
                this.editVisible = false;
                updategoods(this.update).then(res => {
                    if (res.returnCode == 200) {
                        this.tablist();
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                    } else {
                        this.$message.success(`修改第 ${this.idx + 1} 行失败`);
                    }
                });
                this.$set(this.tableData, this.idx, this.form);
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageNum', val);
                this.tablist();
            },
            browser(index, row) {
                layer.open({
                    type: 2,
                    title: '预览页',
                    shadeClose: false,
                    shade: 0.8,
                    area: ['380px', '90%'],
                    content: ['http://travel.cqshuying.com/detail?priceId=' + row.id, 'yes'] //iframe的url
                });
            }
        }
    };
</script>
<!-- css样式实现 -->
<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
